package link.jfire.simplerpc.client;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import link.jfire.baseutil.collection.ByteCache;
import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.fose.Fose;
import link.jfire.simplerpc.exception.InvokeException;
import link.jfire.socket.socketclient.listen.ClientChannelInfo;
import link.jfire.socket.socketclient.listen.GetReadResult;
import link.jfire.socket.socketserver.bus.BusinessCommand;

public class RpcResult implements GetReadResult
{
    protected ThreadLocal<Fose> lbseLocal = new ThreadLocal<Fose>() {
        @Override
        protected Fose initialValue()
        {
            return new Fose();
        }
    };
    private static Logger       logger    = ConsoleLogFactory.getLogger();
    private static RpcResult    instance  = new RpcResult();
    
    private RpcResult()
    {
    
    }
    
    public static RpcResult getInstance()
    {
        return instance;
    }
    
    @Override
    public void handlerException(Throwable e, ClientChannelInfo channelInfo)
    {
        if (e instanceof ClosedChannelException || e instanceof IOException)
        {
        
        }
        else
        {
            logger.error("通道{}出现异常", channelInfo.getAddress(), e);
        }
    }
    
    @Override
    public Object getRequestResult(ByteCache cache, byte command, byte result)
    {
        logger.debug("收到传输结果，进行解析");
        if (result == BusinessCommand.REQUEST_FAIL)
        {
            throw new InvokeException("调用远程失败", (Throwable) lbseLocal.get().deserialize(cache));
        }
        return lbseLocal.get().deserialize(cache);
    }
    
    @Override
    public void receivePushMsg(ByteCache cache, byte command, byte result)
    {
        // TODO Auto-generated method stub
        
    }
    
}
